<script lang="tsx">
import { defineComponent, onMounted, ref } from 'vue';
import { ElButton } from 'element-plus';
import { $t } from '@vben/locales';
import { usePage } from '#/hooks/page/usePage';
import { Pencil, Trash2 } from '@vben/icons';
import deleteIcon from '#/assets/images/delete-icon.png';
import EditDialog from './modules/competition-mgr/edit-dialog.vue';
import { getCompGroupPageApi, deleteCompGroupApi } from '#/api/competition/competitionCtgr';
import { queryMatchListApi } from '#/api/competition/competition-list';
import dayjs from 'dayjs'

export default defineComponent({
  name: 'CompetitionListPage',
  setup() {
    // 弹窗相关状态
    const showDialog = ref(false);
    const dialogMode = ref<'add' | 'edit'>('add');
    const dialogFormData = ref<any>({}); // 弹窗表单数据

    const competitionSelectList = ref<any[]>([]); // 大赛列表

    // 表格列配置
    const columns = [
      { prop: 'name', label: $t('competition.groupName'), minWidth: 120, showOverflowTooltip: true },
      { prop: 'compName', label: $t('competition.belongCompetition'), minWidth: 300, showOverflowTooltip: true },
      {
        prop: 'realName', label: $t('competition.isRealNameInfo'), minWidth: 80, showOverflowTooltip: true,
        formatter: (row: any) => {
          return row.realName ? $t('common.yesTxt') : $t('common.noTxt')
        }
      },
      {
        prop: 'registrationInstructions', label: $t('competition.registrationInstructions'), minWidth: 300, showOverflowTooltip: true,
        formatter: (row: any) => {
          return row.registrationInstructions || '--'
        }
      },
      {
        prop: 'introduction', label: $t('competition.introduction'), minWidth: 200, showOverflowTooltip: true,
        formatter: (row: any) => {
          return row.introduction || '--'
        }
      },
      { prop: 'creator', label: $t('competition.creator'), minWidth: 150, showOverflowTooltip: true },
      {
        prop: 'createTime', label: $t('common.createTimeTxt'), minWidth: 180, showOverflowTooltip: true,
        formatter: (row: any) => {
          return dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
        }
      },
    ];

    // 查询区配置
    const queryColumns = [
      { prop: 'groupName', label: $t('competition.groupName'), type: 'input', placeholder: $t('common.inputPhTxt') },
      {
        prop: 'compId',
        label: $t('competition.belongCompetition'),
        type: 'select',
        placeholder: $t('common.selectPhTxt'),
        options: competitionSelectList.value
      },
    ];

    // API配置
    const API = {
      get: getCompGroupPageApi,
      delete: deleteCompGroupApi,
    };

    // 操作按钮配置
    const commands = [
      {
        key: 'put',
        width: 40,
        icon: Pencil,
        render: (row: any) => (
          <el-tooltip
            effect="dark"
            content={$t('common.editTxt', [''])}
            show-after={600}
            placement="top"
          >
            <span class='edit-btn-wrapper'>
              <el-button icon={Pencil} link onClick={() => handleEdit(row)}></el-button>
              {row.draft && <span class="draft-dot"></span>}
            </span>
          </el-tooltip>
        ),
      },
      {
        key: 'delete',
        width: 40,
        label: $t('common.deleteTxt', ['']),
        icon: Trash2,
      },
    ];

    const deleteProps = {
      title: '',
      message: `
        <div style="display: flex; align-items: center;">
          <img src="${deleteIcon}" style="width: 48px; height: 48px; margin-right: 10px;" />
          <span>${$t('competition.deleteMessageTip')}</span>
        </div>
      `,
      confirmButtonText: $t('common.confirm'),
      cancelButtonText: $t('common.cancel'),
      customClass: 'delete-dialog',
      dangerouslyUseHTMLString: true,
      center: false,
    };

    // 使用页面表格hooks
    const {
      render,
      getTableData,
      queryState
    } = usePage({
      operateProps: {
        fixed: 'right',
        width: '88px'
      },
      API,
      columns,
      queryColumns,
      commands,
      deleteProps,
    });

    // 获取大赛下拉选项
    const getCompetitionSelectList = async () => {
      const res = await queryMatchListApi();
      const newCompetitionOptions = res.map((item: any) => {
        return {
          label: item.matchName,
          value: item.id
        }
      })
      competitionSelectList.value = newCompetitionOptions;

      // 更新查询区配置中的大赛选项
      const compColumn = queryState.columns.find((col: any) => col.prop === 'compId');
      if (compColumn) {
        compColumn.options = newCompetitionOptions;
      }
    };
    // 新增按钮事件
    const handleAdd = () => {
      dialogMode.value = 'add';
      dialogFormData.value = { name: '', compId: '', introduction: '', personCount: 5 };
      showDialog.value = true;
      getCompetitionSelectList();
    };
    // 编辑按钮事件
    const handleEdit = (row: any) => {
      dialogMode.value = 'edit';
      if (row.draft) {
        dialogFormData.value = {
          ...JSON.parse(row.draft)
        };
      } else {
        dialogFormData.value = { ...row };
      }
      showDialog.value = true;
      getCompetitionSelectList();
    };

    // 弹窗操作成功回调
    const handleDialogSuccess = () => {
      showDialog.value = false;
      dialogFormData.value = {};
      getTableData(); // 刷新表格数据
    };

    // 弹窗点击取消
    const handleDialogCancel = () => {
      showDialog.value = false;
      dialogFormData.value = {};
    };

    onMounted(() => {
      getCompetitionSelectList();
    })

    return () => (
      <div>
        {render({
          header: (
            <ElButton type="primary" onClick={handleAdd}>
              {$t('common.addTxt')}
            </ElButton>
          ),
        })}
        <EditDialog
          modelValue={showDialog.value}
          formData={dialogFormData.value}
          mode={dialogMode.value}
          parentTreeOptions={competitionSelectList.value}
          onUpdate:modelValue={(val: boolean) => showDialog.value = val}
          onSuccess={handleDialogSuccess}
          onCancel={handleDialogCancel}
        />
      </div>

    );
  }
});
</script>
<style scoped>
:deep(.edit-btn-wrapper) {
  position: relative;
  display: inline-block;
  width: 40px;

  .draft-dot {
    position: absolute;
    top: 4px;
    right: 8px;
    width: 8px;
    height: 8px;
    background: #ff3b30;
    border-radius: 50%;
    z-index: 1;
  }
}
</style>
